package com.rtx.express.service.impl;

import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rtx.api.annotation.RtxExpressApi;
import com.rtx.common.Base64Helper;
import com.rtx.common.HttpUtils;
import com.rtx.edi.model.api.bo.ApiMappingInfoBo;
import com.rtx.edi.model.express.bo.ExpressBO;
import com.rtx.edi.model.express.po.PlExpressApi;
import com.rtx.edi.model.express.po.PlExpressApiConfig;
import com.rtx.edi.model.express.po.PlExpressResult;
import com.rtx.edi.platform.synctask.service.impl.ZTKYGatWayService;
import com.rtx.express.service.IExpressService;

@RtxExpressApi(expressApiName = "中通快运")
@SuppressWarnings("all")
//中通在线文档
//https://iop.zto56.com/#/apiDates
@Service("快递接口ztky")
public class ZTKYExpressAPI implements IExpressService{
	
	Logger log = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	ZTKYGatWayService ztkyGatWayService;
	

	@Override
	public void callCreaterOrderAPI(ExpressBO bo) {
		PlExpressApi task = bo.getExpressTask();
		String	result ="";
		try {
			//调用中通快运接口 打印信息
			PlExpressResult expressResult = bo.getExpressResultFillSendAndReceiver();
			
			
			//构造电子面单下单请求参数
			ApiMappingInfoBo ediconfig = bo.getEdiConfig();
			String requestBo = JSON.toJSONString(bo);
			String request = ztkyGatWayService.handel(ediconfig.getApimappingcode(), requestBo);
			//请求中通快运接口
			String createrOrderResultStr = callZTOAPI(bo,request,"ADDELECTRONICORDER","电子面单下单");
			//解析返回响应
			JSONObject createrOrderResult =  JSON.parseObject(createrOrderResultStr);
			String status = createrOrderResult.getString("status");
			JSONObject createOrderData = null;
			if("true".equals(status)){
				createOrderData = createrOrderResult.getJSONObject("data");
				expressResult.setWaybillNo(createOrderData.getString("ewbNo"));
				expressResult.setZtokydispatchSiteCode(createOrderData.getString("dispatchSiteCode"));
				expressResult.setZtokydispatchSiteName(createOrderData.getString("dispatchSiteName"));
				expressResult.setZtokyfirstCenterDispatchName(createOrderData.getString("firstCenterDispatchName"));
				expressResult.setZtokyPrintType(createOrderData.getString("PrintType"));
				expressResult.setZtokyrouteCode(createOrderData.getString("routeCode"));
				expressResult.setZtokysendCenterName(createOrderData.getString("sendCenterName"));
				expressResult.setZtokysendSiteCode(createOrderData.getString("sendSiteCode"));
				expressResult.setZtokysendSiteName(createOrderData.getString("sendSiteName"));
			}else {
				throw new RuntimeException(createrOrderResultStr);
			}
			
			//获取打印模版请求报文
			String printedinfoRequest = createQueryprintedinfoRequest(bo);
			//请求中通快运接口
			String printedinfoResultStr = callZTOAPI(bo,request,"QUERYPRINTEDINFO","获取打印模版信息");
			//解析返回响应
			JSONObject printedinfoResultResult =  JSON.parseObject(printedinfoResultStr);
			String printedinfoResultStatus = printedinfoResultResult.getString("status");
			if("true".equals(printedinfoResultStatus)){
				bo.setCallCreateOrderAPIResult("ok");
				JSONObject printedinfoResultData = createrOrderResult.getJSONObject("data");
				JSONArray routeInfos =  printedinfoResultData.getJSONArray("routeInfo");
				JSONObject routeInfo1 = new JSONObject();
				JSONObject routeInfo2 = new JSONObject();
				JSONObject routeInfo3 = new JSONObject();
				JSONObject routeInfo4 = new JSONObject();
				if(routeInfos !=null) {
					try {
						routeInfo1 = routeInfos.toJavaList(JSONObject.class).get(0);
						routeInfo2 = routeInfos.toJavaList(JSONObject.class).get(1);
						routeInfo3 = routeInfos.toJavaList(JSONObject.class).get(2);
						routeInfo4 = routeInfos.toJavaList(JSONObject.class).get(3);
					} catch (Exception e) {}

					
				}
				
				expressResult.setZtokyserviceType(printedinfoResultData.getString("serviceType"));// 服务类型
				expressResult.setZtokyhewbs(printedinfoResultData.getString("hewbs"));//子单号
				expressResult.setZtokypayMode(printedinfoResultData.getString("payMode"));//支付方法
				expressResult.setZtokyweight(printedinfoResultData.getString("weight"));//重量
				expressResult.setZtokypackageType(printedinfoResultData.getString("packageType"));//包装类型
				expressResult.setZtokyrouteSiteName1(routeInfo1.getString("routeSiteName"));//货区路由名称
				expressResult.setZtokyrouteSiteName2(routeInfo2.getString("routeSiteName"));//货区路由名称
				expressResult.setZtokyrouteSiteName3(routeInfo3.getString("routeSiteName"));//货区路由名称
				expressResult.setZtokyrouteSiteName4(routeInfo4.getString("routeSiteName"));//货区路由名称
				expressResult.setZtokynumberId(routeInfo1.getString("numberId"));//货区路由Id
				expressResult.setZtokydispatchSecondSiteName(printedinfoResultData.getString("dispatchSecondSiteName"));//寄件网点
				expressResult.setZtokydeliveryType(printedinfoResultData.getString("deliveryType"));//送货方式
				expressResult.setZtokypickGoodsMode(printedinfoResultData.getString("pickGoodsMode"));//派送方式
				expressResult.setZtokyqrCode(printedinfoResultData.getString("qrCode"));//二维码
				expressResult.setZtokydispatchStieName(printedinfoResultData.getString("dispatchStieName"));//目的网点名称
				
				
			}else {
				throw new RuntimeException(createrOrderResultStr);
			}
			
			
		} catch (Exception e) {
			log.error("订单-"+task.getExternorderkey()+"-获取中通快运单号失败：" + e.getMessage());
			bo.setMsg("订单-"+task.getExternorderkey()+"-获取中通快运单号失败：" + e.getMessage());
		}
		
	}
	
	/**
	 * 请求中通快运接口
	 * @param bo
	 * @param request
	 * @param method
	 * @param apiDesc
	 * @return
	 * @throws Exception
	 */
	String callZTOAPI(ExpressBO bo,String request,String method,String apiDesc) throws Exception{
		PlExpressApi task = bo.getExpressTask();
		String result = "";
		PlExpressApiConfig config = bo.getEdiConfig().getExpressconfig();
		
		String dataDigestStr = request+config.getZtosign();
		String dataDigest = MD5AndBase64(dataDigestStr);//加密方式--先MD5再Base64
		
		Map param=new HashMap<>();
		param.put("cpcode", config.getZtocpcode());
		param.put("data_digest", dataDigest);
		param.put("msg_type", method);
		param.put("param", request);
		
		String requestUrl = bo.getEdiConfig().getTargetUrl();
		log.info("订单-{}-{}-url-{}-请求：{}",task.getExternorderkey(),apiDesc,requestUrl,request);
		result = HttpUtils.sendPostHttp(requestUrl, param);
		log.info("订单-{}-{}-url-{}-请求返回：{}",task.getExternorderkey(),apiDesc,requestUrl,result);
		return result;
	}
	
	
	/**
	 * 在线文档
	 * https://iop.zto56.com/#/apiDates
	 * 请求示例报文
	 * {"orderNo":"","ecId":""}
	 * @param mappingcode
	 * @param bo
	 * @return
	 */
	String  createQueryprintedinfoRequest(ExpressBO bo) {
		Map<String,Object> request = new HashMap<>();
		request.put("orderNo", bo.getExpressTask().getOrderkey());
		request.put("ecId", bo.getEdiConfig().getExpressconfig().getZtoecid());
		return JSON.toJSONString(request);
	}
	
	//中通签名方式
	public static String MD5AndBase64(String param) throws NoSuchAlgorithmException{
		MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(param.getBytes(Charset.forName("UTF-8")));
        byte b[] = md.digest();
	
		String dataDigest =Base64Helper.encode(b);
		return dataDigest;
	}


	@Override
	public void handleCreaterOrderAPIResponse(ExpressBO bo) {
		// TODO Auto-generated method stub
		
	}

}
